/* 
 * Copyright (c), nFractals Ltd. All Rights Reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package org.parade.distributed;


import java.io.Serializable;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.Before;
import org.parade.Parade;
import org.parade.driver.Driver;

public class CommonThreadTestCase extends TestCase implements Serializable{

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}
	
	
	transient private Driver driverA;
	transient private Driver driverB;
	transient AtomicLong counter;
	
	public CommonThreadTestCase(){
	
	}
	
	public CommonThreadTestCase(Driver driverA, Driver driverB) throws InterruptedException{
		this.driverA = driverA;
		this.driverB = driverB;
		
		basic();
	}
	
	public void testDummy(){
		assertTrue(true);
	}
	
	private void basic() throws InterruptedException{
		counter = new AtomicLong(driverB, new Id("counter"));
		Thread t = new Thread(driverA, new Id("ThreadA")){
			public void run(){
				counter = new AtomicLong(Parade.getDriver(), new Id("counter"));
				counter.getAndIncrement();
				while(counter.get()<2) java.lang.Thread.yield();
				counter.getAndIncrement();
			}
		};
		assertFalse(t.isAlive());
		t.start();
		while(counter.get()<1) java.lang.Thread.yield();
		assertTrue(t.isAlive());
		
		long start = System.currentTimeMillis();
		t.join(500);
		assertTrue(t.isAlive());
		assertTrue(System.currentTimeMillis() - start >=500);
		
		counter.getAndIncrement();
		t.join();

		assertFalse(t.isAlive());
		
		
	}
}
